const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
const querystring = require('querystring');

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);
    const pathname = parsedUrl.pathname;

    // 设置CORS头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

    if (req.method === 'OPTIONS') {
        res.writeHead(200);
        res.end();
        return;
    }

    // 静态文件服务
    if (pathname === '/' || pathname === '/index.html') {
        serveStaticFile('public/index.html', 'text/html', res);
    } else if (pathname === '/list.html') {
        serveStaticFile('public/list.html', 'text/html', res);
    } else if (pathname.startsWith('/public/')) {
        const filePath = pathname.substring(1); // 去掉开头的斜杠
        serveStaticFile(filePath, getContentType(filePath), res);
    }
    // 获取图片列表接口
    else if (pathname === '/getlist' && req.method === 'GET') {
        getImageList(res);
    }
    // 文件上传接口
    else if (pathname === '/upload' && req.method === 'POST') {
        handleFileUpload(req, res);
    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('404 Not Found');
    }
});

// 服务静态文件
function serveStaticFile(filePath, contentType, res) {
    const fullPath = path.join(__dirname, filePath);
    
    fs.readFile(fullPath, (err, data) => {
        if (err) {
            res.writeHead(404, { 'Content-Type': 'text/plain' });
            res.end('File not found');
        } else {
            res.writeHead(200, { 'Content-Type': contentType });
            res.end(data);
        }
    });
}

// 获取内容类型
function getContentType(filePath) {
    const ext = path.extname(filePath).toLowerCase();
    const contentTypes = {
        '.html': 'text/html',
        '.css': 'text/css',
        '.js': 'application/javascript',
        '.png': 'image/png',
        '.jpg': 'image/jpeg',
        '.jpeg': 'image/jpeg',
        '.gif': 'image/gif'
    };
    return contentTypes[ext] || 'application/octet-stream';
}

// 获取图片列表
function getImageList(res) {
    const uploadDir = path.join(__dirname, 'public/upload');
    
    fs.readdir(uploadDir, (err, files) => {
        if (err) {
            res.writeHead(500, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ error: '无法读取上传目录' }));
        } else {
            // 过滤出图片文件
            const imageFiles = files.filter(file => {
                const ext = path.extname(file).toLowerCase();
                return ['.png', '.jpg', '.jpeg', '.gif'].includes(ext);
            });
            
            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify(imageFiles));
        }
    });
}

// 处理文件上传
function handleFileUpload(req, res) {
    const uploadDir = path.join(__dirname, 'public/upload');
    
    // 确保上传目录存在
    if (!fs.existsSync(uploadDir)) {
        fs.mkdirSync(uploadDir, { recursive: true });
    }

    let body = [];
    req.on('data', (chunk) => {
        body.push(chunk);
    });

    req.on('end', () => {
        const data = Buffer.concat(body);
        const boundary = req.headers['content-type'].split('boundary=')[1];
        
        if (!boundary) {
            res.writeHead(400, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ error: '无效的请求格式' }));
            return;
        }

        const parts = data.toString().split('--' + boundary);
        
        for (let part of parts) {
            if (part.includes('filename=')) {
                const filenameMatch = part.match(/filename="([^"]+)"/);
                if (filenameMatch) {
                    const filename = filenameMatch[1];
                    const fileDataStart = part.indexOf('\r\n\r\n') + 4;
                    const fileDataEnd = part.lastIndexOf('\r\n');
                    const fileData = part.substring(fileDataStart, fileDataEnd);
                    
                    const fileBuffer = Buffer.from(fileData);
                    const filePath = path.join(uploadDir, filename);
                    
                    fs.writeFile(filePath, fileBuffer, (err) => {
                        if (err) {
                            res.writeHead(500, { 'Content-Type': 'application/json' });
                            res.end(JSON.stringify({ error: '文件保存失败' }));
                        } else {
                            res.writeHead(200, { 'Content-Type': 'application/json' });
                            res.end(JSON.stringify({ success: true, filename: filename }));
                        }
                    });
                    return;
                }
            }
        }
        
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ error: '未找到文件数据' }));
    });
}

// 启动服务器
const PORT = 3000;
server.listen(PORT, () => {
    console.log(`HTTP服务器运行在 http://localhost:${PORT}`);
    console.log(`上传页面: http://localhost:${PORT}/index.html`);
    console.log(`图片列表: http://localhost:${PORT}/list.html`);
});